package com.betty.cscams.service.impl;

import com.betty.cscams.common.page.MybatisPageHelper;
import com.betty.cscams.common.page.PageRequest;
import com.betty.cscams.common.page.PageResult;
import com.betty.cscams.dao.BusTermMapper;
import com.betty.cscams.dao.PsyScoreMapper;
import com.betty.cscams.dao.SysDeptMapper;
import com.betty.cscams.dao.SysUserMapper;
import com.betty.cscams.entity.BusTerm;
import com.betty.cscams.entity.PsyScore;
import com.betty.cscams.entity.SysDept;
import com.betty.cscams.entity.SysUser;
import com.betty.cscams.service.PsyScoreService;
import com.betty.cscams.util.EasyPoiUtil;
import com.betty.cscams.util.SecurityUtils;
import com.betty.cscams.vo.ScoreQueryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;

/**
 * ---------------------------
 *  心理测评成绩Service实现类(PsyScoreServiceImpl)         
 * ---------------------------
 */
@Service
public class PsyScoreServiceImpl implements PsyScoreService {

    @Autowired
    private PsyScoreMapper psyScoreMapper;
    
    @Autowired
    private SysUserMapper sysUserMapper;
    
    @Autowired
    private BusTermMapper busTermMapper;
    
    @Autowired
    private SysDeptMapper sysDeptMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int save(PsyScore record) {
        record.setLastUpdateBy(SecurityUtils.getUsername());
        record.setLastUpdateTime(new Date());
        if(record.getId() == null || record.getId() == 0) {
            // 新增记录
            record.setCreateBy(SecurityUtils.getUsername());
            record.setCreateTime(new Date());
            record.setDelFlag(0);
            return psyScoreMapper.add(record);
        }
        return psyScoreMapper.update(record);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int delete(PsyScore record) {
        return psyScoreMapper.delete(record.getId());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int delete(List<PsyScore> records) {
        for(PsyScore record : records) {
            delete(record);
        }
        return 1;
    }

    @Override
    public PsyScore findById(Long id) {
        return psyScoreMapper.findById(id);
    }

    @Override
    public PageResult findPage(PageRequest pageRequest) {
        SysUser sysUser = sysUserMapper.findByName(SecurityUtils.getUsername());
        Object name = pageRequest.getParam("name");
        Object deptId = pageRequest.getParam("deptId");
        Object termId = pageRequest.getParam("termId");
        Object status = pageRequest.getParam("status");
        
        // 如果是学生用户，则只显示自己的成绩
        if ("student".equals(sysUser.getType())) {
            return MybatisPageHelper.findPage(pageRequest, psyScoreMapper, "findPage", 
                    null, null, termId, status);
        }
        
        return MybatisPageHelper.findPage(pageRequest, psyScoreMapper, "findPage", 
                name, deptId, termId, status);
    }

    @Override
    public PsyScore findByStudentAndTerm(String studentNum, Long termId) {
        return psyScoreMapper.findByStudentAndTerm(studentNum, termId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void calculateRanking(Long termId, Long deptId) {
        // 查询该班级该学期的所有成绩
        List<PsyScore> scores = psyScoreMapper.selectOrder(termId, deptId);
        
        // 按得分从高到低排序并更新排名
        int rank = 1;
        for (PsyScore score : scores) {
            // 更新排名，直接使用PsyScoreMapper的更新排名方法
            psyScoreMapper.updateOrder(score);
        }
    }

    @Override
    public void exportScores(ScoreQueryBean params, HttpServletResponse response) {
        BusTerm busTerm = busTermMapper.findById(params.getTermId());
        SysDept sysDept = sysDeptMapper.selectByPrimaryKey(params.getDeptId());
        
        List<PsyScore> list = psyScoreMapper.findAllByParams(params);
        
        String title = sysDept.getName() + "心理测评成绩表";
        String sheetName = "心理测评";
        String fileName = sysDept.getName() + "心理测评成绩表.xlsx";
        
        EasyPoiUtil.exportExcel(list, title, sheetName, PsyScore.class, fileName, true, response);
    }
    
    @Override
    public List<PsyScore> findLowScores(Long termId, int threshold) {
        return psyScoreMapper.findLowScores(termId, threshold);
    }
} 